$(function()
{
	$('.calendar_cell_data:not(.calendar_cell_prev_next)').hover(function(){$(this).addClass('calendar_hl');},function(){$(this).removeClass('calendar_hl');});
	var get = location.search;
	var oDate = new Date();
	var sMaxYear = $("select[name=year] > option:last").text(), sMinYear = $("select[name=year] > option:first").text() ;

//---------------------------------------------------------------------------------------------------------------------------

 $('#add_new_remind').click(function(){
	$('#reminder_list').html($('#add_form').html()); 
 });	

//---------------------------------------------------------------------------------------------------------------------------

 $('#for').live('change', function(){
	 if (0 == $(this).val())
	 {
		 $('#div_new_name').html($('#new_name').html());
	 }
	 else
	 {
		 $('#div_new_name').html('');
	 }
 });	

//---------------------------------------------------------------------------------------------------------------------------

 $('.del_remind').click(function(){

		var thisElement = $(this);
		var id = thisElement.attr('id');
		
		$.alerts.okButton = 'Yes';
		$.alerts.cancelButton = 'No'; 
		jConfirm(getResource('DELETE_MG_CONFIRM'), getResource('DELETE_MG_TITLE'), function(r) 
		{
			if (r)
			{ 
				$.ajax(
				{
					type: 'POST',
					url: '/calendar/delete',
					data: 'id=' + encodeURIComponent( id ) ,
					dataType: 'json',
					success: function(r)
					{
					  if (1 == r.ret)
					  {
							$('#row_' + id).hide();
					  }
					}
				});	
			}
		});
	});
	
//---------------------------------------------------------------------------------------------------------------------------
 
	bindOnEscape(function(){
		var editor = $('.edit:first input');
		if (!editor) return;
		parentElement = editor.parent('.edit');
		
		var oldValue = parentElement.attr('lastValue');
		$(editor).val(oldValue);
		$(editor).blur();
			
		if (isEdit())
		endEdit();
	});
	if(get != '')
	{
		var tmp = (get.substr(1)).split('&'), tmp2;
		var param = new Array();
		for(var i=0; i < tmp.length; i++)
		{
			tmp2 = tmp[i].split('='); 
			param[tmp2[0]] = tmp2[1];
		}
		if(param['month'] != undefined)
		{
			oDate.setMonth(param['month']-1);
		}
		if(param['year'] != undefined)
		{
			oDate.setYear(param['year']);
		}
		if(param['day'] != undefined)
		{
			oDate.setDate(param['day']);
		}
	}
	
/*	
	$("#calendar_datepicker").datepicker({
		minDate: new Date(sMinYear,0,1),
		maxDate: new Date(sMaxYear,11,31),
		defaultDate: oDate,
		onSelect: function(dateText, inst)
			{
				var s = new String(dateText);
				s = s.split('/');
				var sMonth = s[0];
				var sDay = s[1];
				var sYear = s[2];
				location.href = "/calendar?month="+sMonth+"&year="+sYear+"&day="+sDay;
			}
	});
	$('.ui-datepicker').css('display','block');
*/	
	$("select[name=month], select[name=year]").change(function()
	{
		var sMonth = $("select[name=month]").val();
		var sYear = $("select[name=year]").val();
		location.href = "/calendar?month="+sMonth+"&year="+sYear;
	});
	
	$(".todo > ul").addClass('height_100');
	$(".todo > ul").sortable({
		placeholder: "ui-state-highlight",
		connectWith: '.todo > ul',
		receive: function(ev, ui)
		{
			var sText = ui.item.text();
			var iIdApp = ui.item.attr('id');
			if(iIdApp)
			{
				iIdApp = iIdApp.split('_');
				iIdApp = iIdApp[1];
			}
			else
			{
				iIdApp='';
			}
			
			var mYearMonth = $(".calendar_hidden").attr('id');
			mYearMonth = mYearMonth.split('_');
			
			var iYear = mYearMonth[0];
			var iMonth = mYearMonth[1];
			
			var iDay = ui.item.parent('ul').parent('div').attr('id');
			iDay = iDay.split('_');
			iDay = iDay[1];
			
			saveAppointment(iIdApp, sText, iYear, iMonth, iDay);
			getAppointment();
			ev.stopPropagation();
		}
	});
	
	$('.todo').click(function()
	{
		$("#appointment").removeClass('calendar_hidden');
		$("#appointment_sortable").removeClass('calendar_hidden');
		
		$('.todo').removeClass('calendar_select');
		$(this).addClass('calendar_select');
		getAppointment();
		$('.calendar_hl').removeClass('calendar_hl');
		if (editable())
		{
			$('#app_dialog').dialog({ minHeight: 300, minWidth: 500, modal:true, title:'Appointments', width:500,  buttons: { "Close": function() { $(this).dialog("close"); }, "Add New": addAppointmentClick } }).dialog('open');
		}
		else
		{
			$('#app_dialog').dialog({ minHeight: 300, minWidth: 500, modal:true, title:'Appointments', width:500,  buttons: { "Close": function() { $(this).dialog("close"); } } }).dialog('open');
		}
	});
	
	//$('#day_'+oDate.getDate()).click();
});

function addAppointmentClick()
{
	if( $(".calendar_select").attr('id') )
	{
		$("#appointment_list").append('<li class="ui-state-default edit"><div></div><input type="text" maxlength="255" /></li>');
		$("#appointment_list").find("input").focus();
		addClick();
	}
}

function addToDay()
{
	var oInput = $("#appointment_list").find("input");
	if(oInput)
	{
		oInput.parent('li').text(oInput.val());
		$('.calendar_select > ul').append('<li></li>');
		$('.calendar_select > ul > li:last').text(oInput.val());
	}
}

function getAppointment()
{
	$("#appointment_list").empty();
	$("#appointment_list > li").remove();
	var li = $('.calendar_select > ul > li');
	var sort = $("#appointment_list");
	for(var i=0, count = li.length; i<count ; ++i)
	{
		sort.append('<li><div></div></li>');
		var last = sort.find('li:last > div');
		last.text( $('.calendar_select > ul > li:eq('+i+')').text() );
		
		var sId = $('.calendar_select > ul > li:eq('+i+')').attr('id');
		if (editable())
		last.parent('li').prepend('<img id="del_'+sId+'" class="icon-delete" src="/i/blank.png" alt="Delete" title="Delete" />');
	}
	if (editable())
	$("#appointment_list > li > img").click(function()
			{
				var mDelId = $(this).attr('id');
				mDelId = mDelId.split('_');
				deleteAppointment(mDelId[2]);
			});
	if (editable())
	$("#appointment_list > li > div").click(function()
	{
		var parentElement = $(this).parent('li');
		parentElement.addClass('edit');
		parentElement.attr('lastValue',$(this).text());
		parentElement.append('<input type="text" maxlength="255" />');
		$(this).next('input').attr('value', $(this).text());
		$(this).text('');
		addClick();
	});
	if (editable())
	$('#appointment_list > li > input').live('keydown', (function(e){
		if(e.keyCode == 13)
		{
			$(this).blur();
		}
	}));
}

function trim(s)
{
    return s.replace(/(^\s+)|(\s+$)/g, "");
}

function saveAppointment(iId, sText, iYear, iMonth, iDay)
{
	$.ajax({
		type: 'POST',
		url: '/calendar/save',
		data: 'id='+encodeURIComponent(iId)+'&text='+encodeURIComponent(sText)+'&year='+encodeURIComponent(iYear)+'&month='+encodeURIComponent(iMonth)+'&day='+encodeURIComponent(iDay),
		dataType: 'json',
		async: false,
		success: function(returnData)
		{
			if (returnData.result == true )
			{
				if(returnData.action == 'create')
				{
					addToDay();
					$('.calendar_select > ul > li:last').attr('id','app_'+returnData.iId);
				}
				else
				{
					$('#app_'+returnData.iId).text( $('#appointment_list').find('input').val() );
				}
				getAppointment();
			}
		}
	});
}

function deleteAppointment(iId)
{
	$.ajax({
		type: 'POST',
		url: '/calendar/delete',
		data: 'id='+encodeURIComponent(iId),
		dataType: 'json',
		async: false,
		success: function(returnData)
		{
			if(returnData.result == true)
			{
				if(returnData.iId)
				{
					$("#del_app_"+iId).parent('li').remove();
					$("#app_"+iId).remove();
				}
			}
			else
			{
				return false;
			}
		}
	});
}

function addClick()
{
	$("#appointment_list").find("input").blur(function()
	{
		var parentElement = $(this).parent('.edit'); 
		parentElement.removeClass('edit');
		if( trim($(this).val() ) == '' )
		{
			$(this).parent('li').remove();
		}
		else
		{
			var mId = $(this).parent('li').find('img').attr('id');
			if(mId)
			{
				mId = mId.split('_');
				mId = mId[2];
			}
			else
			{
				mId='';
			}
			var sText = $(this).val();
			var iDay = $(".calendar_select").attr("id");
			iDay = iDay.split('_');
			
			var mYearMonth = $(".calendar_hidden").attr('id');
			mYearMonth = mYearMonth.split('_');
			
			var iYear = mYearMonth[0];
			var iMonth = mYearMonth[1];

			
			if (parentElement.attr('lastValue') != sText)
			{
				saveAppointment(mId, sText, iYear, iMonth, iDay[1]);
			}
			
			$(this).remove();
			parentElement.children('div').text(sText);
			
		}
	});
	$("#appointment_list").find("input").focus();
}

function editable()
{
	return $('#editable').attr('value') != '0';
}

function bindOnEscape(fn)
{
	$(document).keydown(function(e)
	{
		if (e == null) { // ie
			keycode = event.keyCode;
		} else { // mozilla
			keycode = e.which;
		}
		if(keycode == 27){ // escape
			fn();
		}
	});
}
 

function isEdit()
{
	return ($('#isedit').val() == 'true') ? true : false;
} 